package com.rovinj_server;

import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.rovinj_server.app.MyApplication;

import com.rovinj_server.db.DBManager;
import com.rovinj_server.entity.InventorySub;

import com.rovinj_server.entity.InventoryTaskSub;
import com.rovinj_server.entity.StateSubInfo;
import com.rovinj_server.ui.BlindPlateActivity;
import com.rovinj_server.ui.ExplainActivity;
import com.rovinj_server.ui.InventryActivity;
import com.rovinj_server.ui.KFDActivity;

import com.rovinj_server.ui.TaskActivity;
import com.rovinj_server.ui.TextActivity;
import com.rovinj_server.view.CircleMenuLayout;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {


    @Bind(R.id.id_circle_menu_item_center)
    RelativeLayout mIdCircleMenuItemCenter;
    @Bind(R.id.id_menulayout)
    CircleMenuLayout mIdMenulayout;
    private MyApplication myApp;

    private long exitTime = 0;
    private String[] mItemTexts = new String[]{"盘点","导入","盲★★盘"};
    private int[] mItemImgs = new int[]{R.drawable.pan_64,
            R.drawable.excel_64, R.drawable.mangpan,
    };
    private DBManager mManager;
    private List<InventoryTaskSub> mTaskSubList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

            hidStater();
            initData();
            initSocket();

     
        //startService(new Intent(this, TextService.class));
    }

    private void initData() {
        mIdMenulayout.setMenuItemIconsAndTexts(mItemImgs, mItemTexts);
        mIdMenulayout.setOnMenuItemClickListener(new CircleMenuLayout.OnMenuItemClickListener() {
            @Override
            public void itemClick(View view, int pos) {
                switch (pos) {  //发布任务
                    case 0:
                        Toast.makeText(MainActivity.this, "正在切换页面请稍等", Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(MainActivity.this, TaskActivity.class));
                        break;
                    case 1: //
                     startActivity(new Intent(MainActivity.this, InventryActivity.class));
                        break;
                    case 2:
                        Toast.makeText(MainActivity.this, "正在切换页面请稍等", Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(MainActivity.this, BlindPlateActivity.class));
                        break;
                }
            }//192.168.31.247

            @Override
            public void itemCenterClick(View view) {
             startActivity(new Intent(MainActivity.this, ExplainActivity.class));
              //  startActivity(new Intent(MainActivity.this, KFDActivity.class));
           // startActivity(new Intent(MainActivity.this, TextActivity.class));
            }
        });
    }


    /**
     * 隐藏状态栏
     */
    private void hidStater() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.hide();
    }

    public String buffer = "";

    public void initSocket() {
        mManager = new DBManager(MainActivity.this);
        mManager.copyDBFile();

       // final String postData = JSON.toJSONString(map);
        final String str = "提交任务接受成功";
        new Thread() {
            public void run() {
                Bundle bundle = new Bundle();
                bundle.clear();
                OutputStream output;
                try {
                    ServerSocket serverSocket = new ServerSocket(30000);
                    while (true) {
                        Message msg = new Message();
                        msg.what = 66;
                        try {
                            Socket socket = serverSocket.accept();
                            output = socket.getOutputStream();
                            output.write(str.getBytes("UTF-8"));
                            output.flush();
                            socket.shutdownOutput();
                            BufferedReader bff = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                            String line = null;
                            buffer = "";
                            while ((line = bff.readLine()) != null) {
                                buffer = line + buffer;
                            }
                            bundle.putString("msg", buffer.toString());
                            msg.setData(bundle);
                            mHandler.sendMessage(msg);
                            bff.close();
                            output.close();
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }.start();
    }

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 66) {
                Bundle bundle = msg.getData();
                String str = bundle.getString("msg");
                Log.d("---------服务端开启", str);
                 initThread(str);
            }
        }
    };

    public void initThread(final String str) {
         new Thread(new Runnable() {
             @Override
             public void run() {
                 Log.d("---------子线程", str);
                 Gson gson = new Gson();
                 StateSubInfo stateSubInfo = gson.fromJson(str, StateSubInfo.class);
                 List<InventorySub> stateSubDataList = stateSubInfo.getStateSubDataList();
                 if(stateSubDataList!=null &&stateSubDataList.size()>0){
                  mManager.insertTsakSubData(stateSubDataList);
                 List<InventoryTaskSub> taskSubList = mManager.findTaskSubList();
                 Log.d("-------taskSubList", taskSubList.size()+"");
                 for (int i = 0; i < taskSubList.size(); i++) {
                     String location = taskSubList.get(i).getLocation();
                     String state = taskSubList.get(i).getState();
                     Log.d("------taskSubListtaskSubList", location+"" +state);
                 }
                 }
             }
         }).start();
    }

    private void shuJu() {
        if (mTaskSubList != null) {
            for (int i = 0; i < mTaskSubList.size(); i++) {
                mManager.updateQtyNullData(mTaskSubList.get(i).getId(), mTaskSubList.get(i).getDiscNumber());
            }
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis() - exitTime) > 2000){
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                MyApplication.getInstance().exit();

            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private String getlocalip() {   //获取ID
        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int i = wifiInfo.getIpAddress();
        System.out.println("int ip " + i);
        if (i == 0) return null;
        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);

    }
}
